/**
 * 303. Range Sum Query - Immutable
 * https://leetcode.com/problems/range-sum-query-immutable/description/
 *
 * @author Kevin
 * @date 2018-12-25
 */
public class NumArray {

    private SegmentTree<Integer> segmentTree;

    public NumArray(int[] nums) {
        Integer[] data = new Integer[nums.length];
        for (int i = 0; i < nums.length; i++) {
            data[i] = nums[i];
        }

        this.segmentTree = new SegmentTree<>(data, (a, b) -> a + b);
    }

    /**
     * 求区间内的和
     *
     * @param i
     * @param j
     * @return
     */
    public int sumRange(int i, int j) {
        if (segmentTree == null) {
            throw new IllegalArgumentException("Segment Tree is null");
        }

        return segmentTree.query(i, j);
    }

    /**
     * 根据索引修改对应的值
     *
     * @param i
     * @param val
     */
    public void update(int i, int val) {
        if (segmentTree == null) {
            throw new IllegalArgumentException("Error");
        }

        segmentTree.set(i, val);
    }

    public static void main(String[] args) {
        int[] nums = {-2, 0, 3, -5, 2, -1};
        NumArray numArray = new NumArray(nums);
        System.out.println(numArray.sumRange(0, 2));
        System.out.println(numArray.sumRange(2, 5));
        System.out.println(numArray.sumRange(0, 5));

        int[] nums1 = {1, 3, 5};
        numArray = new NumArray(nums1);
        System.out.println(numArray.sumRange(0, 2));
        numArray.update(1, 2);
        System.out.println(numArray.sumRange(0, 2));
    }

}
